from fastapi import Request, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware  
from fastapi.middleware.trustedhost import TrustedHostMiddleware

from app.settings.config import (
    CORS_ORIGINS,
    CORS_METHODS,
    CORS_HEADERS,
    CORS_CREDENTIALS,
    ALLOWED_HOSTS,
)


def path_matches_pattern(request_path: str, pattern: str) -> bool:
    """
    检查请求路径是否与给定的通配符模式匹配。
    
    :param request_path: 请求的路径
    :param pattern: 带有通配符的模式，例如 "/static/*"
    :return: 如果匹配返回True，否则返回False
    """
    if pattern.endswith("/*"):
        # 处理以/*结尾的模式
        base_path = pattern[:-2]  # 去掉/*
        return request_path.startswith(base_path)
    return request_path == pattern



# 自定义http中间件
async def http_middleware(request: Request, call_next):
    """自定义http中间件"""
    
    # 排除特定路径
    excluded_patterns = ["/static/*"]  # 需要排除的路径
    if any(path_matches_pattern(request.url.path, pattern) for pattern in excluded_patterns):
        return await call_next(request)  # 直接处理请求，不经过鉴权


    # 检查请求路径是否为/home
    if request.url.path == "/home":
        return Response(status_code=202)  # 返回202状态码

    token = request.headers.get("Authorization")
    print("token",token)


    response: Response = await call_next(request)
    return response

def init_middleware(app):
    app.add_middleware(
            CORSMiddleware,
            allow_origins=CORS_ORIGINS,
            allow_methods=CORS_METHODS,
            allow_headers=CORS_HEADERS,
            allow_credentials=CORS_CREDENTIALS,
        )
    # 添加GZip中间件以压缩响应
    # app.add_middleware(GZipMiddleware, minimum_size=1000, compresslevel=4, exclude_paths=[])
    app.add_middleware(GZipMiddleware, minimum_size=1000, compresslevel=4)

    # 添加受信任主机中间件
    app.add_middleware(
        TrustedHostMiddleware,
        allowed_hosts=ALLOWED_HOSTS  # 允许的主机
    )
    # 添加自定义鉴权中间件
    app.middleware("http")(http_middleware)